I have had good success using late binding method and then the reference does not need to be set in VBA.
Initially I develop using Early Binding by setting the reference so that I have the intellisense for the coding but I then convert to Late Binding.
You only need to re-dimension the variables to Object and find the constant values to dimension them. You can find the constant values by opening the Immediate window (while the reference is still set) and then as per the following example.
?olMailItem
The following is an example of opening Outlook from another Office application and using Late Binding. You will see that I have attempted GetObject before CreateObject. Documentation indicates that you should be able to just use CreateObject and if Outlook
is already open then not a problem. However, I have identified a problem where it creates multiple Processes if Outlook is busy receiving or sending mail at the critical time of CreateObject and the method I have used eliminates that.
Code has been tested in Office 2010, 2007, 2003 and 2002
Private Sub btnLateBindMethod_Click()
'Use following Dim statements for Late Binding
'NOTE: Additional Const declaration
Dim objOutlook As Object 'Outlook.Application (Note dimensioned as Object)
Dim objEmail As Object 'Outlook.MailItem (Note dimensioned as Object)
Dim objNameSpace As Object 'Outlook.NameSpace (Note dimensioned as Object)
Const olMailItem As Long = 0 'For Late Binding
Const olFolderInbox As Long = 6 'For Late Binding
Const olFormatHTML As Long = 2 'For Late Binding
Dim strSubject As String
Dim strAddress As String
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
On Error GoTo 0 'Resume error trapping ASAP
If objOutlook Is Nothing Then
Set objOutlook = CreateObject("Outlook.Application")
Set objNameSpace = objOutlook.GetNamespace("MAPI")
objNameSpace.GetDefaultFolder(olFolderInbox).Display
End If
Set objEmail = objOutlook.CreateItem(olMailItem)
strSubject = "My Test Message"
With objEmail
'.To = strToAddress 'Removed for privacy
.Subject = strSubject
.BodyFormat = olFormatHTML
.Display
'Full Name of window can change depending on Tools -> Options -> Mail Format
'Changing this option for outgoing mail changes the window name.
'However, AppActivate appears not to require entire name but needs up to end
'of - Message which is included in heading following the Subject string
'irrespective of the Mail Format option chosen.
AppActivate (strSubject & " - Message")
End With
End Sub